import 'dart:io';
import 'dart:math';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:light_compressor/light_compressor.dart';
import 'package:photo_frame/net/http_manager.dart';
import 'package:photo_frame/utils/a_logger.dart';
import 'package:photo_manager/photo_manager.dart';
// import 'package:video_compress/video_compress.dart';

final List<String> assetIds = [
  "DF02D333-08D1-4D0C-B6B9-28F717F765ED/L0/001",
  "E34E7069-B24F-45CF-B22B-8FF7C28C214A/L0/001",
  "A444DA04-E874-47F9-83FE-9D0AC68A209E/L0/001",
  "FD403412-D9D7-4EEA-9978-99A4AE81B776/L0/001",
  "3CA8A2C4-EB14-48F9-A21B-97E95FF2EDBE/L0/001",
  "5AA47E86-B5CF-462E-9E70-D41B92DFEE6F/L0/001",
  "C657E818-3B60-413C-B029-93D7062712AE/L0/001",
  "C515B6E6-21AA-4DDD-8F5D-BDB4F4214532/L0/001",
  "2E3AD0F3-3C3D-46D9-9A24-F1BD535B80CC/L0/001",
  "40EB1122-039A-4875-81C6-952FB0703A38/L0/001",
  "3D57A85C-B2D9-41EA-81A8-D41D052F9AE5/L0/001",
  "sdsdsj",
  "sdjfslfjsldjfslfjslk",
  "sdjsljflsjflsjflskjfldskjf",
  "dsjfljslkjfdsjfslkjfklsj",
  "sdljfosjfldsjflskfjslkdfjl",
  "2259A494-2109-4B40-8BF0-42CE7720C47E/L0/001",
  "F8BF81BC-2183-4FFE-A353-3DA035CF988C/L0/001",
  "994CA569-09B9-4462-BC9B-95C5AE60F75B/L0/001",
  "305954E8-89B9-4C5E-8379-93FD93B03AFF/L0/001",
];

class AssetTransModel {
  int? id; // 数据库主键
  String? assetId; // 相片资源
  String? toFrameId; // 要传送到的设备 id
  String? toFrameName; // 要穿的设备名
  String? toFrameFolderName; // 要传送的相册名字
  String? markDesc; // 备注;
  String? transDate; // 2024/01/01 时间戳
  String? uploadUrl;
  String? batchId;
  double progress = 0;
  int transStatus = 0; // 0: 未传输, 1: 传输中 2: 传输失败

  AssetTransModel();

  Map<String, dynamic> toMap() {
    Map<String, dynamic> map = {
      'assetId': assetId ?? "",
      'toFrameId': toFrameId ?? "",
      'toFrameName': toFrameName ?? "",
      'toFrameFolderName': toFrameFolderName ?? "",
      'markDesc': markDesc ?? "",
      'transDate': transDate ?? "",
      'batchId': batchId,
      'transStatus': transStatus,
    };
    if (id != null) {
      map["id"] = id!;
    }
    return map;
  }

  String get uuid => (assetId ?? "") + (batchId ?? "");

  factory AssetTransModel.fromMap(Map<String, dynamic> map) {
    AssetTransModel model = AssetTransModel();
    model.assetId = map['assetId'];
    model.toFrameId = map['toFrameId'];
    model.toFrameName = map['toFrameName'];
    model.toFrameFolderName = map['toFrameFolderName'];
    model.markDesc = map['markDesc'];
    model.transDate = map['transDate'];
    model.batchId = map['batchId'];
    model.transStatus = map['transStatus'];
    model.id = map["id"];
    return model;
  }

  upload(bool compress, void Function(double, String) progessCallBack) async {
    if (assetId == null || assetId!.isEmpty) {
      transStatus = 2;
      throw ErrorDescription("无效资源");
    }
    AssetEntity? asset = await AssetEntity.fromId(assetId!);
    if (asset == null) {
      transStatus = 2;
      throw ErrorDescription("无效资源");
    }
    String mimeType =
        asset.type == AssetType.video ? "video/mp4" : "image/jpeg";
    var file = await asset.file;
    asset.file.then((e) {
      ALogger.e("sadasdas ${e?.path ?? ""}");
    });
    var suffix = file?.path.substring(file.path.lastIndexOf(".") + 1);
    if (suffix?.isNotEmpty != true) {
      suffix = asset.type == AssetType.video ? "mp4" : "jpg";
    }
    if (uploadUrl == null) {
      var response = await HttpManager.instance
          .doRequest("/api/getuploadurl", parameters: {
        "id": asset.id,
        "ext": ".$suffix",
        "folder": toFrameFolderName ?? "",
        "frame_id": toFrameId,
        "title": markDesc
      });
      if (!response.isSuccess) {
        transStatus = 2;
        throw ErrorDescription("获取上传地址失败");
      }
      uploadUrl = response.data?["url"];
    }
    if (uploadUrl == null || uploadUrl!.isEmpty) {
      transStatus = 2;
      throw ErrorDescription("获取上传地址失败");
    }
    if (asset.type == AssetType.video) {
      File? file = await asset.file;
      if (file == null) {
        transStatus = 2;
        throw ErrorDescription("获取上传地址失败");
      }

      // MediaInfo? compressedVideo;
      Result? compressedVideo;
      if (compress) {
        try {
          // compressedVideo = await VideoCompress.compressVideo(
          //   file.path,
          //   quality: VideoQuality.DefaultQuality,
          //   frameRate: 24,
          // );

          compressedVideo = await LightCompressor().compressVideo(
            path: file.path,
            videoQuality: VideoQuality.high,
            isMinBitrateCheckEnabled: false,
            video: Video(
                videoName:
                    'MyVideo-${DateTime.now().millisecondsSinceEpoch}.mp4'),
            android:
                AndroidConfig(isSharedStorage: false, saveAt: SaveAt.Movies),
            ios: IOSConfig(saveInGallery: false),
          );
        } catch (e) {
          ALogger.e(e);
        }

        // if (compressedVideo == null ||
        //     compressedVideo.path == null ||
        //     compressedVideo.file == null) {
        //   transStatus = 2;
        //   throw ErrorDescription("压缩视频失败");
        // }
        if (compressedVideo is OnFailure) {
          transStatus = 2;
          throw ErrorDescription("压缩视频失败 ${compressedVideo.message}");
        }
      }
      var res = await HttpManager.instance.dio.request(
        uploadUrl!,
        options: Options(method: "PUT", headers: {
          // Headers.contentLengthHeader: file!.lengthSync(),
          Headers.contentTypeHeader: mimeType,
          // or the appropriate content type
        }),

        data: await File(compress
                ? (compressedVideo as OnSuccess).destinationPath
                : file.path)
            .readAsBytes(),
        // data: formData,
        onSendProgress: (count, total) {
          double p = count * 1.0 / total;
          if (p - progress > 0.1) {
            progress = p;
            progessCallBack(p, uuid);
          }
          if (count == total) {
            progress = 1;
            progessCallBack(1.0, uuid);
          }
        },
      );
      print(res);
    } else {
      var compressJPEG = await FlutterImageCompress.compressWithList(
        (await asset.originBytes) as Uint8List,
        minWidth: 1280,
        minHeight: 800,
        autoCorrectionAngle: false,
        quality: 95,
      );
      await HttpManager.instance.dio.request(
        uploadUrl!,
        options: Options(method: "PUT", headers: {
          'Content-Type': mimeType, // or the appropriate content type
        }),
        data: compressJPEG,
        onSendProgress: (count, total) {
          double p = count * 1.0 / total;
          if (p - progress > 0.4) {
            progress = p;
            progessCallBack(p, uuid);
          }
          if (count == total) {
            progress = 1;
            progessCallBack(1.0, uuid);
          }
        },
      );
    }
    transStatus = 1;
  }
}
